﻿var url;
var currentRole;
var currentUser;
var helper = new Helper();
var isNewNonHR = true;
var isNewRole = true;

jQuery(function () {

    jQuery('#userManagementMenu').addClass('active');
    jQuery('#UserTab').tabs({
        onSelect: function (title, index) {
            if (index == 0) {
                getUserToGrid();
            }
            else if (index == 1) {
                jQuery('#dgRole').datagrid({
                    url: "/service/api.ashx?metdhodName=getAllRole",
                    loadFilter: pagerFilter,
                    onDblClickRow: function (index, fields, value) {

                        currentUser = fields.UserName;
                        currentRole = fields.RoleName;
                        editRole(fields);
                    }
                });
            }
            return false;
        }
    });
    getUserToGrid();
});

function getUserToGrid() {
    jQuery('#dgUser').datagrid({
        url: "/service/api.ashx?metdhodName=getAllUser",
        onDblClickRow: function (index, fields, value) {
            editNonHR(fields);
        }
    });
}
function editRole(currentRole) {
    isNewRole = false;
    if (currentRole == undefined) {
        currentRole = jQuery('#dgRole').datagrid('getSelected');
    }
    if (currentRole != undefined) {
        jQuery('#dlgRole').dialog('open').dialog('setTitle', 'แก้ไข Role');
        jQuery('#roleName').val(currentRole.Name);
        jQuery('#roleEnable').prop('checked', currentRole.IsActive);
    }
}
function addNonHR() {
    isNewNonHR = true;
    jQuery('#dlgNonHr').dialog('open').dialog('setTitle', 'เพิ่มข้อมูลพนักงานใหม่');
}

function addRole() {
    jQuery('#dlgRole').dialog('open').dialog('setTitle', 'เพิ่มระดับการใช้งาน');
}

function editNonHR(editUser) {

    if (editUser == undefined || editUser == null) {
        editUser = jQuery('#dgUser').datagrid('getSelected')
    }

    if (editUser == undefined || editUser == null) {
        return false;
    }
    else {
        isNewNonHR = false;
        jQuery('#dlgNonHr').dialog('open').dialog('setTitle', 'แก้ไขข้อมูลพนักงาน');
        bindUser(editUser);
    }
}

function deleteNonHR(currentRole) {
    jQuery.messager.confirm('ต้องการจะลบ User?', 'ลบข้อมูลผู้ใช้งานในระบบ', function (r) {
        if (r) {
            var user = jQuery('#dgUser').datagrid('getSelected');
            jQuery.post('/service/api.ashx?metdhodName=deleteUser', {
                username: user.UserName
            }, function (result) {
                jQuery('#dgUser').datagrid('reload');
                alert(result);
            }, 'text');
        }
    });
}

function deleteRole() {

    jQuery.messager.confirm('ต้องการจะลบ Role?', 'ข้อมูลพนักงานที่ใช้สิทธิ์ role นี้อยู่จะโดนลบไปด้วย ', function (r) {
        if (r) {
            var role = jQuery('#dgRole').datagrid('getSelected');
            jQuery.post('/service/api.ashx?metdhodName=deleteRole', {
                roleid: role.Id
            }, function (result) {
                jQuery('#dgRole').datagrid('reload');
                alert(result);
            }, 'text');
        }
    });

}


function saveRole() {
    var roleName = jQuery('#roleName').val();
    var roleActive = jQuery('#roleEnable').is(':checked');

    if (validateRole(roleName, roleActive)) {
        if (isNewRole) {
            jQuery.post('/service/api.ashx?metdhodName=addRole', {
                rolename: roleName,
                isactive: roleActive,
            }, function (result) {
                jQuery('#dgRole').datagrid('reload');
                alert(result);
                jQuery('#roleName').val('');
                jQuery('#dlgRole').dialog('close');
            }, 'text');
        } else {

            jQuery.post('/service/api.ashx?metdhodName=editRole', {
                rolename: roleName,
                isactive: roleActive,
            }, function (result) {
                jQuery('#dgRole').datagrid('reload');
                jQuery('#roleName').val('');
                jQuery('#dlgRole').dialog('close')
                alert(result);
            }, 'text');
        }
    }
}

function validateRole(roleName, roleActive) {
    if (roleName == null || roleName == undefined || roleName == "") {
        alert("กรุณาระบุชื่อ Role");
        return false;
    }
    else if (roleActive == null || roleActive == undefined) {
        alert("กรุณาระบุสถานะ Role");
        return false;
    }
    return true;
}

function pagerFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function') {	// is array
        data = {
            total: data.length,
            rows: data
        };
    }
    var dg = jQuery(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
}

function formatDate(val, row) {
    if (val === null || val === '') {
        return null;
    }
    else {
        var d = new Date(parseInt(val.substr(6)));
        return jQuery.datepicker.formatDate('dd-MM-yy', d) + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    }
}

function formatCheckbox(val, row) {
    if (row.IsActive === null || row.IsActive === '') {
        return '<div class="ui-icon ui-icon-check" style="">false</div>';
    }
    else {
        if (row.IsActive) {
            return '<div class="ui-icon ui-icon-check" style="">true</div>';
        }
        else {
            return '<div class="ui-icon ui-icon-check" style="">false</div>';
        }
    }
}

function searchUser() {
    var keyword = jQuery('#searcKeyword').val();
    var searchType = jQuery('#searchType').combobox('getValue');
    jQuery('#dg').datagrid({
        url: "/service/api.ashx?metdhodName=getalluserrole&keyword=" + escape(keyword) + "&searchType=" + searchType,
        loadFilter: pagerFilter,
        onDblClickRow: function (index, fields, value) {

            currentUser = fields.UserName;
            currentRole = fields.RoleName;
            editRole(fields);
        }
    });
}

function bindUser(user) {
    jQuery('#username').val(user.UserName);
    jQuery('#password').val(user.Password);
    jQuery('#rePassword').val(user.Password);
    jQuery('#email').val(user.Email);
    jQuery('#fullname').val(user.FullName);
    jQuery('#userRole').combobox('setValue',user.Role);
    jQuery('#phone').val(user.Telephone);
    jQuery('#fax').val(user.Fax);
    jQuery('#isactive').prop('checked', user.Active);
}
function saveNonHR() {
    var d = getAllInput();
    if (validateUser(d)) {
        if (d[0].isactive == "on") {
            d[0].isactive = true;
        }

        if (isNewNonHR) {

            jQuery.post('/service/api.ashx?metdhodName=addUser', {
                data: d,
            }, function (result) {
                getUserToGrid();
                alert(result);
                jQuery('#dlgNonHr').dialog('close');
                clearAllInput();
            }, 'text');

        }
        else {
            jQuery.post('/service/api.ashx?metdhodName=editUser', {
                data: d,
            }, function (result) {
                getUserToGrid();
                alert(result);
                jQuery('#dlgNonHr').dialog('close');
                clearAllInput();
            }, 'text');

        }
        
    }
}

function validateUser(data) {
    data = data[0];
    if (data.username == null || data.username == undefined || data.username == "") {
        alert("กรุณาระบุ Username");
        return false;
    }
    else if (data.password == null || data.password == undefined || data.password.length < 4) {
        alert("Password ต้องมากกว่า 4 ตัวอักษร");
        return false;
    }
    else if (data.password != data.rePassword) {
        alert("Re Password ไม่ถูกต้อง");
        return false;
    }
    else if (data.email == null || data.email == undefined || data.email == "") {
        alert("กรุณาระบุ Email");
        return false;
    }
    else if (data.fullname == null || data.fullname == undefined || data.fullname == "") {
        alert("กรุณาระบุชื่อ");
        return false;
    }
    else if (data.userRole == null || data.userRole == undefined || data.userRole == "") {
        alert("กรุณาระบุ Role");
        return false;
    }
    
    return true;
}

function getAllInput() {
    var datas = [];
    var data = {};
    jQuery("form#FormNonHr :input").each(function () {
        var input = jQuery(this); // This is the jquery object of the input, do what you will
        var name = jQuery(input).attr("name");
        var type = jQuery(input).attr("type");
        if (type == 'checkbox') {
            var value;
            value = input.prop('checked');
            data[name] = value;
        }
        else if (name != undefined) {
            var value;
            value = input.val();
            data[name] = value;
        }
    });
    datas.push(data);
    return datas;
}


function clearAllInput() {
    
    jQuery("form#FormNonHr :input").each(function () {
        var input = jQuery(this); // This is the jquery object of the input, do what you will
        input.val('');
        return true;
    });
}